package model

import (
	"context"
	"parking-lot-go-push/config"
	"parking-lot-go-push/logger"

	"fmt"
	"time"

	"github.com/go-redis/redis"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// mysql
var Db *gorm.DB
var err error

// mongdb
var MongoDb *mongo.Database
var mongoDbErrLogger = logger.NewLogger("mongodb", "err")

// redis
var RedisClient *redis.Client
var RedisCtx = context.Background()

func init() {
	mysqlInit()
	mongdbInit()
}

func mysqlInit() {
	// 读取配置文件
	dbSection := config.Cfg.Section("DATABASE")

	dbHost := dbSection.Key("DB_HOST").String()
	dbPort := dbSection.Key("DB_PORT").String()
	dbName := dbSection.Key("DB_DATABASE").String()
	dbUsername := dbSection.Key("DB_USERNAME").String()
	dbPassword := dbSection.Key("DB_PASSWORD").String()

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		dbUsername, dbPassword, dbHost, dbPort, dbName)

	Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})

	if err != nil {
		panic(err.Error())
	}
}

func mongdbInit() {
	// 读取配置文件
	mongodbSection := config.Cfg.Section("MONGODB")

	mongodbHost := mongodbSection.Key("DB_HOST").String()
	mongodbPort := mongodbSection.Key("DB_PORT").String()
	mongodbName := mongodbSection.Key("DB_DATABASE").String()
	mongodbUsername := mongodbSection.Key("DB_USERNAME").String()
	mongodbPassword := mongodbSection.Key("DB_PASSWORD").String()

	// 创建一个上下文对象
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// 创建一个MongoDB的客户端
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%s@%s:%s", mongodbUsername, mongodbPassword, mongodbHost, mongodbPort)))
	if err != nil {
		mongoDbErrLogger.Error(fmt.Sprintf("初始化服务失败:%s", err.Error()))
		panic(err.Error())
	}

	// 检查连接是否成功
	err = client.Ping(ctx, nil)
	if err != nil {
		mongoDbErrLogger.Error(fmt.Sprintf("连接服务失败:%s", err.Error()))
		panic(err.Error())
	}

	// 选择数据库
	MongoDb = client.Database(mongodbName)
}
